<template>
  <div id="divbox">
    <div class="login-form">

      <div id="logo">
        <div
          style="font-family: 'Microsoft YaHei';letter-spacing: 0.5px; font-weight: bold; font-size: 40px;text-align: center">
          &nbsp; <span style="color:rgb(137, 204, 255) ;">修改用户</span>
        </div>
      </div>

      <el-form ref="refform" :model="form" status-icon :rules="rules" label-width="80px">

        <el-form-item label="编号id" prop="id">
          <el-input :disabled="true" v-model="form.id" class="input"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" class="input"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickName">
          <el-input type="nickName" v-model="form.nickName" class="input"></el-input>
        </el-form-item>


        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" class="input"></el-input>
        </el-form-item>


        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" class="input"></el-input>
        </el-form-item>


        <el-form-item label="用户头像" prop="icon">
          <img :src="form.icon" class="icon" style="text-align: left">
        </el-form-item>

        <el-form-item :class="{ hide: hideUpload }">
          <el-upload ref="upload" action="#" multiple :limit="limit" :file-list="dataForm.imgFileList"
                     list-type="picture-card" :on-preview="handlePictureCardPreview" :on-change="OnChange"
                     :on-remove="handleRemove" :on-exceed="handleExceed" accept="image/jpeg,image/png"
                     :auto-upload="false">
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
              上传文件，最多上传1张且单张图片不超过5M
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt=""/>
          </el-dialog>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitUpload()">上传图片</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="updateUser('refform')" style="width: 150px;">提交</el-button>
          <el-button type="primary" @click="returnUser()" style="width: 150px;">返回</el-button>
          <!--          <router-link to="updateUser">点击返回</router-link>-->
        </el-form-item>
        <br/>
      </el-form>
    </div>
  </div>
</template>

<script>
  export default {
    data () {
      var phone = (rule, value, callback) => {
        var reg = /^1[3456789]\d{9}$/
        if (value === '') {
          callback(new Error('请输入手机号'))
        } else if (value !== '') {
          if (!reg.test(value)) {
            callback(new Error('手机号格式不正确'))
          }
          callback()
        } else {
          callback()
        }
      }

      var nickName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入昵称'))
        } else if (this.form.nickName !== '') {
          var reg = /^.{5,10}$/
          if (!reg.test(value)) {
            callback(new Error('文本长度在5到10之间'))
          }
          callback()
        }
        callback()
      }

      var userName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入姓名'))
        } else if (this.form.userName !== '') {
          var reg = /^[\u4E00-\u9FA5]{2,4}$/
          if (!reg.test(value)) {
            callback(new Error('2-4个汉字'))
          }
          callback()
        }
        callback()
      }

      var email = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请正确填写邮箱'))
        } else if (value !== '') {
          var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.([a-zA-Z0-9_-])+)+$/
          if (!reg.test(value)) {
            callback(new Error('请输入有效的邮箱'))
          }
          callback()
        } else {
          callback()
        }
      }

      var icon = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请上传头像'))
        } else {
          if (this.form.icon !== '') {
            // this.$refs.reffrom.validateField('nickName')
          }
          callback()
        }
      }
      return {
        form: {
          id: 0,
          phone: '',
          nickName: '',
          userName: '',
          icon: '',
          email: ''
        },
        dataForm: {
          imgFileList: [],
        },
        ruleForm: {
          companyName: '',
          companyLogo: ''
        },
        rules: {
          phone: [
            {validator: phone, trigger: 'blur'}
          ],
          nickName: [
            {validator: nickName, trigger: 'blur'}
          ],
          userName: [
            {validator: userName, trigger: 'blur'}
          ],
          email: [
            {validator: email, trigger: 'blur'}
          ],
          icon: [
            {validator: icon, trigger: 'blur'}
          ],
        },
        //图片上传的参数
        visible: false,
        uploadUrl: '',
        dialogImageUrl: '',
        dialogVisible: false,
        limit: 1,
        hideUpload: false, //是否显示上传图片的加号
        deleteImgFileList: [], //存已被删除了的图片的id
      }
    },
    created () {
      this.form = this.$route.query.form
    },
    methods: {
      //点击上传图片
      submitUpload () {
        let formData = new FormData() //  用FormData存放上传文件
        this.dataForm.imgFileList.forEach((file) => {
          formData.append('file', file.raw)
        })
        this.$http.postRequestPicture('updateFile/updateFile/updateFile', formData, 'multipart/form-data').then(res => {
          console.log(res)
          if (res.data.code == 200) {
            //返回200 重新赋值
            this.form.icon = res.data.data
          } else {
            this.$message(res.message)
          }
        }).catch(err => {
          this.$message.info(err)
        })

      },
      //预览图片时
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      OnChange (file, fileList) {
        this.dataForm.imgFileList.push(file)
        this.hideUpload = fileList.length >= this.limit
      },
      //删除图片时
      handleRemove (file, fileList) {
        if (file.id) {
          console.log('删除了已被上传过的图片')
          console.log(file.id)
          this.deleteImgFileList.push(file.id)
        }
        this.dataForm.imgFileList = fileList
        this.hideUpload = fileList.length >= this.limit
      },
      //文件超出个数限制时
      handleExceed (files, fileList) {
        this.$message.warning(
          `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
            } 个文件`
        )
      },
      //【修改】
      updateUser (reffrom) {
        //数据向后端发送进行验证
        //$refs是一个引用
        this.$refs[reffrom].validate((valid) => {
          if (valid) {
            var data = {
              phone: this.form.phone,
              nickName: this.form.nickName,
              userName: this.form.userName,
              icon: this.form.icon[0],
              email: this.form.email,
              id: this.form.id
            }
            this.$http.getRegister('user/wx/updateUser', data).then(res => {
              if (res.data.code == 200) {
                this.$message({showClose: true, message: '恭喜你，账户修改成功✔', type: 'success'})
                let timer = setTimeout(() => {
                  //跳转登录页面
                  this.$router.push('/ser')
                }, 3000)
                // 离开当前页面时销毁定时器
                this.$once('hook:beforeDestroy', () => {
                  clearInterval(timer)
                  timer = null
                })
              }
              this.$message(res.data.message)
            }).catch(err => {
              this.$message.info(err)
            })
          }
        })
      },
      //返回按钮
      returnUser () {
        this.$router.push('/ser')
      }

    }
  }
</script>

<style scoped>
  #divbox {
    width: 100%;
    height: 160vh;
    /*将🎀页面背景  图片路径替换为你自己的图片路径*/
    background-image: url("https://image-img.oss-cn-chengdu.aliyuncs.com/2022-03-12/b923d0630782b4e46dcbb2121.jpg");
    /*保持图片比例并完全覆盖元素*/
    background-size: cover;
    background-position: center center;
    /*将图片居中对齐*/
  }

  .login-form {
    width: 442px;
    max-height: 950px;
    background-color: rgba(248, 242, 235, 0.5);
    position: relative;
    left: 455px;
    top: 50px;
  }

  #logo {
    width: 100%;
    height: 60px;
    background-color: aquamarine;
    margin-bottom: 30px;
  }

  .input {
    max-width: 300px;
    margin: auto;
  }

  .icon {
    border-radius: 50%;
    width: 100px;
    /*position: absolute;*/
    /*left: 638px;*/
    top: 0px;
  }

</style>
